<template>
  <el-dialog
      v-model="visible"
      :title="isEdit ? '编辑预设' : '保存为预设'"
      width="1000px"
      @close="handleClose"
      class="save-preset-dialog"
  >
    <el-form :model="formData" :rules="rules" ref="formRef" label-width="120px" size="default">
      <!-- 基本信息 -->
      <div class="form-section">
        <h4 class="section-title">
          <el-icon><Document /></el-icon>
          基本信息
        </h4>

        <el-form-item label="预设名称" prop="name">
          <el-input
              v-model="formData.name"
              placeholder="请输入预设名称"
              clearable
              maxlength="50"
              show-word-limit
          />
        </el-form-item>

        <el-form-item label="预设描述" prop="description">
          <el-input
              v-model="formData.description"
              type="textarea"
              :rows="3"
              placeholder="请输入预设描述（可选）"
              maxlength="200"
              show-word-limit
          />
        </el-form-item>
      </div>

      <!-- 画布设置 -->
      <div class="form-section">
        <h4 class="section-title">
          <el-icon><Monitor /></el-icon>
          画布设置
        </h4>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="画布宽度" prop="canvas_width">
              <el-input-number
                  v-model="formData.canvas_width"
                  :min="480"
                  :max="3840"
                  :step="1"
                  style="width: 100%;"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="画布高度" prop="canvas_height">
              <el-input-number
                  v-model="formData.canvas_height"
                  :min="480"
                  :max="3840"
                  :step="1"
                  style="width: 100%;"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 常用尺寸快捷按钮 -->
        <div class="size-presets">
          <span class="preset-label">常用尺寸：</span>
          <el-button-group size="small">
            <el-button @click="setCanvasSize(1080, 1920)">竖屏 9:16</el-button>
            <el-button @click="setCanvasSize(1920, 1080)">横屏 16:9</el-button>
            <el-button @click="setCanvasSize(1080, 1080)">方形 1:1</el-button>
            <el-button @click="setCanvasSize(1200, 1600)">4:3</el-button>
          </el-button-group>
        </div>
      </div>

      <!-- 数字人设置 -->
      <div class="form-section">
        <h4 class="section-title">
          <el-icon><User /></el-icon>
          数字人设置
        </h4>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="缩放比例">
              <el-slider
                  v-model="formData.video_scale"
                  :min="0.1"
                  :max="3.0"
                  :step="0.1"
                  :show-input="true"
                  input-size="small"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="水平位置">
              <el-input-number
                  v-model="formData.video_x"
                  :min="-1000"
                  :max="1000"
                  :step="10"
                  style="width: 100%;"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="垂直位置">
              <el-input-number
                  v-model="formData.video_y"
                  :min="-1000"
                  :max="1000"
                  :step="10"
                  style="width: 100%;"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="保持宽高比">
              <el-switch
                  v-model="formData.keep_human_ratio"
                  active-text="保持"
                  inactive-text="拉伸"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <!-- 背景设置 -->
      <div class="form-section">
        <h4 class="section-title">
          <el-icon><Picture /></el-icon>
          背景设置
        </h4>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="缩放比例">
              <el-slider
                  v-model="formData.bg_scale"
                  :min="0.1"
                  :max="3.0"
                  :step="0.1"
                  :show-input="true"
                  input-size="small"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="水平位置">
              <el-input-number
                  v-model="formData.bg_x"
                  :min="-1000"
                  :max="1000"
                  :step="10"
                  style="width: 100%;"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="垂直位置">
              <el-input-number
                  v-model="formData.bg_y"
                  :min="-1000"
                  :max="1000"
                  :step="10"
                  style="width: 100%;"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="保持宽高比">
              <el-switch
                  v-model="formData.keep_bg_ratio"
                  active-text="保持"
                  inactive-text="拉伸"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <!-- 参数预览 -->
      <div class="form-section">
        <h4 class="section-title">
          <el-icon><View /></el-icon>
          参数预览
        </h4>

        <div class="params-preview">
          <div class="preview-group">
            <span class="preview-label">画布:</span>
            <el-tag size="small">{{ formData.canvas_width }}×{{ formData.canvas_height }}</el-tag>
            <el-tag size="small" type="success">{{ formData.output_format?.toUpperCase() }}</el-tag>
          </div>

          <div class="preview-group">
            <span class="preview-label">数字人:</span>
            <el-tag size="small" type="info">缩放 {{ formData.video_scale }}</el-tag>
            <el-tag size="small" type="info">位置 ({{ formData.video_x }}, {{ formData.video_y }})</el-tag>
            <el-tag size="small" :type="formData.keep_human_ratio ? 'success' : 'warning'">
              {{ formData.keep_human_ratio ? '保持比例' : '拉伸填充' }}
            </el-tag>
          </div>

          <div class="preview-group">
            <span class="preview-label">背景:</span>
            <el-tag size="small" type="warning">缩放 {{ formData.bg_scale }}</el-tag>
            <el-tag size="small" type="warning">位置 ({{ formData.bg_x }}, {{ formData.bg_y }})</el-tag>
            <el-tag size="small" :type="formData.keep_bg_ratio ? 'success' : 'warning'">
              {{ formData.keep_bg_ratio ? '保持比例' : '拉伸填充' }}
            </el-tag>
          </div>
        </div>
      </div>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button @click="resetForm" v-if="!isEdit">
          <el-icon><Refresh /></el-icon>
          重置
        </el-button>
        <el-button type="primary" @click="handleSave" :loading="saving">
          <el-icon><Check /></el-icon>
          {{ isEdit ? '更新' : '保存' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import {Monitor} from "@element-plus/icons-vue";

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  params: {
    type: Object,
    default: () => ({})
  },
  preset: {
    type: Object,
    default: null
  }
})

const emit = defineEmits(['update:modelValue', 'save'])

// 计算属性
const visible = computed({
  get: () => props.modelValue,
  set: (value) => {
    emit('update:modelValue', value)
  }
})

const isEdit = computed(() => !!props.preset?.id)

// 响应式数据
const formRef = ref(null)
const saving = ref(false)

const formData = ref({
  name: '',
  description: '',
  canvas_width: 1080,
  canvas_height: 1920,
  output_format: 'mp4',
  video_scale: 1.0,
  video_x: 0,
  video_y: 0,
  bg_scale: 1.0,
  bg_x: 0,
  bg_y: 0,
  keep_human_ratio: true,
  keep_bg_ratio: true
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入预设名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  canvas_width: [
    { required: true, message: '请输入画布宽度', trigger: 'blur' },
    { type: 'number', min: 480, max: 3840, message: '宽度范围: 480-3840', trigger: 'blur' }
  ],
  canvas_height: [
    { required: true, message: '请输入画布高度', trigger: 'blur' },
    { type: 'number', min: 480, max: 3840, message: '高度范围: 480-3840', trigger: 'blur' }
  ],
  output_format: [
    { required: true, message: '请选择输出格式', trigger: 'change' }
  ]
}

// 监听props变化
watch(() => props.params, (newParams) => {
  if (newParams && Object.keys(newParams).length > 0) {
    // 从参数中提取预设数据，排除输出文件名
    const { output_name, ...presetParams } = newParams
    Object.assign(formData.value, presetParams)
  }
}, { immediate: true, deep: true })

watch(() => props.preset, (newPreset) => {
  if (newPreset) {
    // 编辑模式，加载现有预设数据
    Object.assign(formData.value, {
      name: newPreset.name || '',
      description: newPreset.description || '',
      canvas_width: newPreset.canvas_width || 1080,
      canvas_height: newPreset.canvas_height || 1920,
      output_format: newPreset.output_format || 'mp4',
      video_scale: newPreset.video_scale || 1.0,
      video_x: newPreset.video_x || 0,
      video_y: newPreset.video_y || 0,
      bg_scale: newPreset.bg_scale || 1.0,
      bg_x: newPreset.bg_x || 0,
      bg_y: newPreset.bg_y || 0,
      keep_human_ratio: newPreset.keep_human_ratio !== false,
      keep_bg_ratio: newPreset.keep_bg_ratio !== false
    })
  } else if (!isEdit.value) {
    // 新建模式，重置名称和描述
    formData.value.name = ''
    formData.value.description = ''
  }
}, { immediate: true })

// 监听弹窗显示状态
watch(visible, (newVal) => {
  if (newVal) {
    // 弹窗打开时重置表单验证状态
    if (formRef.value) {
      formRef.value.clearValidate()
    }

    // 如果是新建模式且没有名称，生成默认名称
    if (!isEdit.value && !formData.value.name) {
      formData.value.name = generateDefaultName()
    }
  }
})

// 方法
const setCanvasSize = (width, height) => {
  formData.value.canvas_width = width
  formData.value.canvas_height = height
  ElMessage.success(`画布尺寸已设置为 ${width}×${height}`)
}

const resetForm = () => {
  formData.value = {
    name: generateDefaultName(),
    description: '',
    canvas_width: 1080,
    canvas_height: 1920,
    output_format: 'mp4',
    video_scale: 1.0,
    video_x: 0,
    video_y: 0,
    bg_scale: 1.0,
    bg_x: 0,
    bg_y: 0,
    keep_human_ratio: true,
    keep_bg_ratio: true
  }

  if (formRef.value) {
    formRef.value.clearValidate()
  }

  ElMessage.success('表单已重置')
}

const handleSave = async () => {
  if (!formRef.value) return

  try {
    const valid = await formRef.value.validate()
    if (!valid) return

    saving.value = true

    const saveData = { ...formData.value }

    // 如果是编辑模式，保留ID
    if (isEdit.value) {
      saveData.id = props.preset.id
    }

    emit('save', saveData)
    handleClose()

  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    saving.value = false
  }
}

const handleClose = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  visible.value = false
}

// 生成默认预设名称
const generateDefaultName = () => {
  const timestamp = new Date().toLocaleDateString('zh-CN').replace(/\//g, '-')
  const time = new Date().toLocaleTimeString('zh-CN', { hour12: false }).replace(/:/g, '')
  return `预设_${timestamp}_${time}`
}
</script>

<style lang="scss" scoped>
.save-preset-dialog {
  ::v-deep(.el-dialog) {
    .el-dialog__body {
      max-height: 70vh;
      overflow-y: auto;
    }
  }
}

.form-section {
  margin-bottom: 30px;
  padding: 20px;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  background: #fafafa;

  &:last-child {
    margin-bottom: 0;
  }
}

.section-title {
  margin: 0 0 20px 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 8px;
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 10px;
}

.size-presets {
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid #ebeef5;
  display: flex;
  align-items: center;
  gap: 10px;

  .preset-label {
    color: #606266;
    font-size: 14px;
    white-space: nowrap;
  }
}

.params-preview {
  .preview-group {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 12px;

    &:last-child {
      margin-bottom: 0;
    }

    .preview-label {
      font-weight: 500;
      color: #606266;
      min-width: 60px;
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

::v-deep(.el-form-item) {
  margin-bottom: 20px;

  .el-form-item__label {
    color: #606266;
    font-weight: 500;
  }
}

::v-deep(.el-slider) {
  .el-slider__input {
    width: 80px;
  }
}

::v-deep(.el-input-number) {
  .el-input__inner {
    text-align: center;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .form-section {
    padding: 16px;
  }

  .size-presets {
    flex-direction: column;
    align-items: stretch;

    .preset-label {
      margin-bottom: 8px;
    }
  }

  .params-preview {
    .preview-group {
      flex-direction: column;
      align-items: flex-start;
      gap: 6px;

      .preview-label {
        min-width: auto;
      }
    }
  }
}
</style>